package work;

import com.rabbitmq.client.*;
import org.junit.Test;
import util.ConnUtil;

import java.io.IOException;

/**
 * @author TZL
 * @date 2020/8/13
 */
public class Consumer {
    @Test
    public void consume1() throws Exception {
        //1. 获取连接对象Conn
        Connection conn = ConnUtil.getConn();
        //2. 创建channel
        Channel channel = conn.createChannel();
        //3. 声明队列 Queue
        channel.queueDeclare(Publisher.QUEUE_NAME,true,false,false,null);
        //3.5  Qos
        channel.basicQos(1);
        //4. 消费当前队列 consume
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者1号消费了："+new String(body));
                //ask
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Publisher.QUEUE_NAME,false,consumer);
        //5. 释放资源
        System.in.read();
        channel.close();
        conn.close();
    }

    @Test
    public void consume2() throws Exception {
        //1. 获取连接对象Conn
        Connection conn = ConnUtil.getConn();
        //2. 创建channel
        Channel channel = conn.createChannel();
        //3. 声明队列 Queue
        channel.queueDeclare(Publisher.QUEUE_NAME,true,false,false,null);
        //3.5  Qos
        channel.basicQos(1);
        //4. 消费当前队列 consume
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者2号消费了："+new String(body));
                //ask
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Publisher.QUEUE_NAME,false,consumer);
        //5. 释放资源
        System.in.read();
        channel.close();
        conn.close();
    }

}
